<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import axios from 'axios'

const router = useRouter()
const authStore = useAuthStore()

// 创建用户数据的副本，以便编辑
const user = ref({...authStore.user})
const loading = ref(false)
const message = ref('')
const messageType = ref('')
const passwordData = ref({
  userId: authStore.user?.userId,
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const showPasswordForm = ref(false)
const passwordLoading = ref(false)

// 消息图标
const messageIcon = computed(() => {
  return messageType.value === 'success' 
    ? 'fas fa-check-circle' 
    : 'fas fa-exclamation-circle'
})

// 使用计算属性动态生成头像URL
const avatarPreview = computed(() => {
  if (!user.value?.avatar?.imageName) return null
  return `http://localhost:8080/api/image/${user.value.avatar.imageName}`
})

// 格式化出生日期
if (user.value?.birthDate) {
  // 将日期格式转换为 YYYY-MM-DD
  const birthDate = new Date(user.value.birthDate)
  user.value.birthDate = birthDate.toISOString().split('T')[0]
}

// 确保性别有默认值
if (!user.value.gender) {
  user.value.gender = 'male'
}

onMounted(async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  // 加载最新的用户数据
  try {
    await authStore.fetchUserProfile()
    user.value = {...authStore.user}
    
    // 确保性别有默认值
    if (!user.value.gender) {
      user.value.gender = 'male'
    }
    
    // 格式化出生日期
    if (user.value?.birthDate) {
      const birthDate = new Date(user.value.birthDate)
      user.value.birthDate = birthDate.toISOString().split('T')[0]
    }
  } catch (error) {
    console.error('Failed to fetch user profile:', error)
    message.value = '加载用户信息失败'
    messageType.value = 'error'
  }
})

const handleSubmit = async () => {
  if (loading.value) return
  
  loading.value = true
  message.value = ''
  
  try {
    // 构建更新数据，确保不修改登录名，并保留status字段
    const updateData = {
      userId: user.value.userId,
      loginName: user.value.loginName, // 不可修改，但需要传回服务器
      name: user.value.name,
      gender: user.value.gender,
      birthDate: user.value.birthDate,
      phone: user.value.phone,
      email: user.value.email,
      description: user.value.description,
      status: user.value.status || 'approved', // 确保status字段不为null
      password: user.value.password,
      lastModifiedDate: new Date()
    }
    
    const response = await axios.put('/api/user/update', updateData)
    
    if (response.data.success) {
      message.value = '个人资料更新成功'
      messageType.value = 'success'
      
      // 更新本地缓存的用户信息
      await authStore.fetchUserProfile()
    } else {
      message.value = response.data.message || '更新个人资料失败'
      messageType.value = 'error'
    }
  } catch (error) {
    console.error('Failed to update profile:', error)
    message.value = error.response?.data?.message || '更新个人资料失败'
    messageType.value = 'error'
  } finally {
    loading.value = false
  }
}

const handlePasswordSubmit = async () => {
  if (passwordLoading.value) return
  
  // 验证密码
  if (passwordData.value.newPassword !== passwordData.value.confirmPassword) {
    message.value = '两次输入的新密码不一致'
    messageType.value = 'error'
    return
  }
  
  if (passwordData.value.newPassword.length < 6) {
    message.value = '新密码长度不能少于6位'
    messageType.value = 'error'
    return
  }
  
  passwordLoading.value = true
  message.value = ''
  
  try {
    // 设置用户ID
    passwordData.value.userId = user.value.userId
    
    const response = await axios.put('/api/user/change-password', passwordData.value)
    
    if (response.data.success) {
      message.value = '密码修改成功'
      messageType.value = 'success'
      
      // 清空密码表单
      passwordData.value = {
        userId: user.value.userId,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      
      // 关闭密码表单
      showPasswordForm.value = false
    } else {
      message.value = response.data.message || '密码修改失败'
      messageType.value = 'error'
    }
  } catch (error) {
    console.error('Failed to change password:', error)
    message.value = error.response?.data?.message || '密码修改失败'
    messageType.value = 'error'
  } finally {
    passwordLoading.value = false
  }
}

const togglePasswordForm = () => {
  showPasswordForm.value = !showPasswordForm.value
  message.value = ''
}

const handleAvatarChange = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!allowedTypes.includes(file.type)) {
    message.value = '只支持 JPG、PNG、GIF 格式的图片'
    messageType.value = 'error'
    return
  }
  
  // 验证文件大小（2MB）
  if (file.size > 2 * 1024 * 1024) {
    message.value = '图片大小不能超过2MB'
    messageType.value = 'error'
    return
  }
  
  try {
    loading.value = true
    message.value = ''
    
    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', user.value.userId)
    
    // 上传图片
    const response = await axios.post('/api/image/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.success) {
      // 更新用户头像信息
      user.value.avatar = { 
        imageId: response.data.imageId,
        imagePath: response.data.imagePath,
        imageName: response.data.imageName
      }
      
      // 刷新用户信息，确保头像信息同步到全局状态
      await authStore.fetchUserProfile()
      
      message.value = '头像上传成功'
      messageType.value = 'success'
    } else {
      message.value = response.data.message || '头像上传失败'
      messageType.value = 'error'
    }
  } catch (error) {
    console.error('Failed to upload avatar:', error)
    message.value = error.response?.data?.message || '头像上传失败'
    messageType.value = 'error'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="profile-container">
    <!-- 顶部标题和提示信息 -->
    <div class="profile-header">
      <div class="header-content">
        <h1 class="profile-title">个人资料</h1>
        <p class="profile-subtitle">管理您的账号信息和隐私设置</p>
      </div>
      
      <!-- 提示消息 -->
      <div v-if="message" :class="['message-banner', messageType]">
        <i :class="messageIcon"></i>
        {{ message }}
      </div>
    </div>
    
    <div class="profile-layout">
      <!-- 左侧：头像和用户名展示 -->
      <div class="profile-sidebar">
        <div class="avatar-section">
          <div class="avatar-container">
            <img 
              :src="avatarPreview || '/default-avatar.png'" 
              alt="用户头像" 
              class="user-avatar"
            />
            <div class="avatar-overlay">
              <label for="avatar-upload" class="avatar-upload-label">
                <i class="fas fa-camera"></i>
                <span>更换头像</span>
              </label>
            </div>
          </div>
          
          <input 
            type="file" 
            id="avatar-upload" 
            class="avatar-upload-input" 
            accept="image/jpeg,image/png,image/gif"
            @change="handleAvatarChange"
          />
          
          <h2 class="user-name">{{ user.name }}</h2>
          <p class="user-id">ID: {{ user.loginName }}</p>
          
          <!-- 修改密码按钮 -->
          <button 
            class="password-toggle-btn"
            @click="togglePasswordForm"
          >
            <i class="fas fa-lock"></i>
            修改密码
          </button>
        </div>
      </div>
      
      <!-- 右侧：个人信息表单 -->
      <div class="profile-content">
        <!-- 修改密码表单 -->
        <div v-if="showPasswordForm" class="card password-form-card">
          <h2 class="card-title">
            <i class="fas fa-key"></i>
            修改密码
          </h2>
          
          <form @submit.prevent="handlePasswordSubmit" class="password-form">
            <!-- 旧密码 -->
            <div class="form-group">
              <label for="old-password">当前密码</label>
              <input 
                v-model="passwordData.oldPassword" 
                type="password" 
                id="old-password" 
                required
                placeholder="请输入当前密码"
              />
            </div>
            
            <!-- 新密码 -->
            <div class="form-group">
              <label for="new-password">新密码</label>
              <input 
                v-model="passwordData.newPassword" 
                type="password" 
                id="new-password" 
                required
                placeholder="请设置至少6位的新密码"
              />
            </div>
            
            <!-- 确认新密码 -->
            <div class="form-group">
              <label for="confirm-password">确认新密码</label>
              <input 
                v-model="passwordData.confirmPassword" 
                type="password" 
                id="confirm-password" 
                required
                placeholder="请再次输入新密码"
              />
            </div>
            
            <div class="form-actions">
              <button 
                type="button" 
                class="btn btn-cancel" 
                @click="togglePasswordForm"
                :disabled="passwordLoading"
              >
                取消
              </button>
              <button 
                type="submit" 
                class="btn btn-submit"
                :disabled="passwordLoading"
              >
                <span v-if="!passwordLoading">保存修改</span>
                <span v-else class="loading-spinner-small"></span>
              </button>
            </div>
          </form>
        </div>
        
        <!-- 个人信息表单 -->
        <div v-else class="card profile-form-card">
          <h2 class="card-title">
            <i class="fas fa-user-edit"></i>
            基本信息
          </h2>
          
          <form @submit.prevent="handleSubmit" class="profile-form">
            <!-- 用户名 (只读) -->
            <div class="form-group">
              <label for="login-name">账号</label>
              <input 
                v-model="user.loginName" 
                type="text" 
                id="login-name" 
                disabled
              />
              <small class="form-hint">账号不可修改</small>
            </div>
            
            <!-- 姓名 -->
            <div class="form-group">
              <label for="name">姓名</label>
              <input 
                v-model="user.name" 
                type="text" 
                id="name" 
                required
                placeholder="请输入您的姓名"
              />
            </div>
            
            <!-- 性别 -->
            <div class="form-group">
              <label>性别</label>
              <div class="radio-group">
                <label class="radio-label">
                  <input 
                    type="radio" 
                    name="gender" 
                    value="male" 
                    v-model="user.gender"
                  />
                  <span>男</span>
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    name="gender" 
                    value="female" 
                    v-model="user.gender"
                  />
                  <span>女</span>
                </label>
              </div>
            </div>
            
            <!-- 出生日期 -->
            <div class="form-group">
              <label for="birth-date">出生日期</label>
              <input 
                v-model="user.birthDate" 
                type="date" 
                id="birth-date" 
                required
              />
            </div>
            
            <!-- 电话 -->
            <div class="form-group">
              <label for="phone">手机号</label>
              <input 
                v-model="user.phone" 
                type="tel" 
                id="phone" 
                required
                placeholder="请输入您的手机号码"
              />
            </div>
            
            <!-- 电子邮箱 -->
            <div class="form-group">
              <label for="email">电子邮箱</label>
              <input 
                v-model="user.email" 
                type="email" 
                id="email" 
                required
                placeholder="请输入您的电子邮箱"
              />
            </div>
            
            <!-- 个人简介 -->
            <div class="form-group">
              <label for="description">个人简介</label>
              <textarea 
                v-model="user.description" 
                id="description" 
                rows="4"
                placeholder="请简要介绍一下您自己（可选）"
              ></textarea>
            </div>
            
            <div class="form-actions">
              <button 
                type="submit" 
                class="btn btn-submit"
                :disabled="loading"
              >
                <span v-if="!loading">保存修改</span>
                <span v-else class="loading-spinner-small"></span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

/* 顶部标题区域 */
.profile-header {
  margin-bottom: 2rem;
}

.header-content {
  margin-bottom: 1rem;
}

.profile-title {
  font-size: 2rem;
  color: var(--primary-color);
  margin-bottom: 0.5rem;
}

.profile-subtitle {
  color: var(--text-light);
  font-size: 1rem;
}

/* 消息横幅 */
.message-banner {
  padding: 1rem;
  border-radius: 8px;
  font-weight: 500;
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
}

.message-banner.success {
  background-color: rgba(0, 200, 83, 0.1);
  color: #00c853;
  border-left: 4px solid #00c853;
}

.message-banner.error {
  background-color: rgba(244, 67, 54, 0.1);
  color: #f44336;
  border-left: 4px solid #f44336;
}

.message-banner i {
  margin-right: 0.5rem;
  font-size: 1.25rem;
}

/* 布局 */
.profile-layout {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 2rem;
  align-items: flex-start;
}

/* 侧边栏 */
.profile-sidebar {
  position: sticky;
  top: 2rem;
}

.avatar-section {
  background: linear-gradient(135deg, var(--primary-color-light), var(--primary-color));
  padding: 2rem;
  border-radius: 12px;
  text-align: center;
  color: white;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-container {
  position: relative;
  width: 150px;
  height: 150px;
  margin-bottom: 1.5rem;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-upload-label {
  color: white;
  font-size: 0.9rem;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-upload-label i {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}

.avatar-upload-input {
  display: none;
}

.user-name {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.user-id {
  font-size: 0.9rem;
  opacity: 0.8;
  margin-bottom: 1.5rem;
}

.password-toggle-btn {
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 0.75rem 1.5rem;
  border-radius: 50px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
}

.password-toggle-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.password-toggle-btn i {
  margin-right: 0.5rem;
}

/* 主内容区 */
.profile-content {
  width: 100%;
}

.card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 2rem;
}

.card-title {
  font-size: 1.3rem;
  color: var(--text-color);
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.card-title i {
  margin-right: 0.75rem;
  color: var(--primary-color);
}

/* 表单样式 */
.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: var(--text-color);
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.1);
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.form-hint {
  display: block;
  margin-top: 0.25rem;
  font-size: 0.8rem;
  color: #777;
}

.radio-group {
  display: flex;
  gap: 1.5rem;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-label input {
  margin-right: 0.5rem;
  width: auto;
}

/* 按钮 */
.form-actions {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 120px;
}

.btn-submit {
  background-color: var(--primary-color);
  color: white;
  border: none;
}

.btn-submit:hover {
  background-color: var(--primary-color-dark);
}

.btn-cancel {
  background-color: transparent;
  border: 1px solid #ddd;
  color: var(--text-color);
}

.btn-cancel:hover {
  background-color: #f5f5f5;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 加载中动画 */
.loading-spinner-small {
  display: inline-block;
  width: 1rem;
  height: 1rem;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .profile-layout {
    grid-template-columns: 1fr;
  }
  
  .profile-sidebar {
    position: static;
    margin-bottom: 2rem;
  }
}
</style> 